package com.hdax.dm.auth;

import cn.hutool.json.JSONUtil;
import com.hdax.dm.utils.ResponseUtil;
import com.hdax.dm.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class AuthIntercepter implements HandlerInterceptor {

//    @Override
//    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
//        String token = request.getHeader("token");
//        boolean flag = request.getRequestURI().contains("/p/");
//        if(!flag) return true;
//        return false;
//    }

    @Autowired
    private Token tokens;

//    @Autowired
//    public StringRedisTemplate stringRedisTemplate;
    //请求前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        //token redis校验
        System.out.println("ddd"+tokens);
        if (tokens.token(token).equals("0")){
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println(JSONUtil.toJsonStr(ResponseUtil.returnFail("1305","账号异常，请重新登录")));
            return false;
        }
        return true;


//        System.out.println("使用拦截器");
//        //最常用的登录拦截、或是权限校验、或是防重复提交、或是根据业务像12306去校验购票时间,总之可以去做很多的事情。
//        boolean flag = request.getRequestURI().contains("/p/"); //请求路径 不存在p   直接放行
//        if(!flag) return true;
//        String userId=null;
//        String token1  =request.getHeader("token");
//        try {
//
//            userId = tokens.token(token1);
//        }catch (NullPointerException e){
//            response.setContentType("application/json;charset=UTF-8");
//            PrintWriter out = response.getWriter();
//            out.println(JSONUtil.toJsonStr(ResponseUtil.returnFail("1305","账号异常，请重新登录")));
//            return false;
//        }
//        //redis存储的真实有效的验证码
//        String token = stringRedisTemplate.opsForValue().get(userId);
//        String userId1 = tokens.token(token);
//        if(userId1.equals(userId)) {
//            return  true;
//        }else{
//            response.setContentType("application/json;charset=UTF-8");
//            PrintWriter out = response.getWriter();
//            out.println(JSONUtil.toJsonStr(ResponseUtil.returnFail("1305","账号异常，请重新登录")));
//            return false;
//        }
//        //先根据请求的token 去 redis  进行判断
//        // 根据 token  解密  获取用户id
    }
}
